package com.jou.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileDownServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取下载路径（在这个地方写死了）
        String realPath="/Users/yan/Documents/IdeaProjects/maven/web1/src/main/resources/1.png";
        //设置下载文件名
        String filename = realPath.substring(realPath.lastIndexOf("//")+1);
        //设置浏览器的下载支持(Content-Disposition)
        resp.setHeader("Content-Disposition","attachment;filename="+filename);
        //获取下载输入流
        FileInputStream inputStream = new FileInputStream(realPath);
        //创建缓冲区
        int len = 0;
        byte [] buffer =new byte[1024];
        //获取outputStream对象
        ServletOutputStream outputStream = resp.getOutputStream();
        //将输出流写到buffer缓冲区，使用输出流将缓冲区的数据传至客户端
        while ((len=inputStream.read(buffer))>0){
            outputStream.write(buffer,0,len);
        }
        //关闭流
        inputStream.close();
        outputStream.close();


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
